"""Main CLI interface for the task manager."""

import argparse
import sys
from .commands import CommandHandler


def create_parser():
    """Create and configure the argument parser."""
    parser = argparse.ArgumentParser(
        prog='cctm',
        description='CC Task Manager - A CLI tool for managing tasks with intelligent text parsing.',
        epilog='Examples:\n'
               '  cctm add "Task 1, Task 2, Task 3"\n'
               '  cctm auto-add\n'
               '  cctm list\n'
               '  cctm done 1,2,3\n'
               '  cctm undo 1\n'
               '  cctm delete 1\n'
               '  cctm delete --all\n'
               '  cctm next\n'
               '  cctm prev\n'
               '  cctm benchmark 5',
        formatter_class=argparse.RawDescriptionHelpFormatter
    )
    
    subparsers = parser.add_subparsers(dest='command', help='Available commands')
    
    # Add command
    add_parser = subparsers.add_parser('add', help='Add tasks from comma-separated list')
    add_parser.add_argument('tasks', help='Comma-separated task names')
    
    # Auto-add command
    auto_add_parser = subparsers.add_parser('auto-add', help='Add tasks interactively with smart parsing')
    
    # List command
    list_parser = subparsers.add_parser('list', help='List all tasks with IDs and status')
    
    # Done command
    done_parser = subparsers.add_parser('done', help='Mark tasks as completed')
    done_parser.add_argument('task_ids', help='Comma-separated task IDs')
    
    # Undo command
    undo_parser = subparsers.add_parser('undo', help='Mark task as todo')
    undo_parser.add_argument('task_id', help='Task ID to mark as todo')
    
    # Delete command
    delete_parser = subparsers.add_parser('delete', help='Delete tasks')
    delete_group = delete_parser.add_mutually_exclusive_group(required=True)
    delete_group.add_argument('task_id', nargs='?', help='Task ID to delete')
    delete_group.add_argument('--all', action='store_true', help='Delete all tasks')
    
    # Next command
    next_parser = subparsers.add_parser('next', help='Show progress and advance to next task')
    
    # Prev command
    prev_parser = subparsers.add_parser('prev', help='Reverse last completion')
    
    # Benchmark command
    benchmark_parser = subparsers.add_parser('benchmark', help='Set starting point for progress messages')
    benchmark_parser.add_argument('task_id', help='Task ID to set as benchmark')
    
    return parser


def main():
    """Main entry point for the CLI."""
    parser = create_parser()
    args = parser.parse_args()
    
    if not args.command:
        parser.print_help()
        sys.exit(1)
    
    handler = CommandHandler()
    
    try:
        if args.command == 'add':
            handler.add_tasks(args.tasks)
        
        elif args.command == 'auto-add':
            handler.auto_add_tasks()
        
        elif args.command == 'list':
            handler.list_tasks()
        
        elif args.command == 'done':
            handler.mark_tasks_done(args.task_ids)
        
        elif args.command == 'undo':
            handler.mark_task_undo(args.task_id)
        
        elif args.command == 'delete':
            if args.all:
                handler.delete_all_tasks()
            else:
                handler.delete_task(args.task_id)
        
        elif args.command == 'next':
            handler.show_next_task()
        
        elif args.command == 'prev':
            handler.show_prev_task()
        
        elif args.command == 'benchmark':
            handler.set_benchmark(args.task_id)
        
    except KeyboardInterrupt:
        print("\nOperation cancelled.")
        sys.exit(1)
    except Exception as e:
        print(f"Error: {e}")
        sys.exit(1)


if __name__ == '__main__':
    main()